package com.lanju.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("deprecation")
public class WeiXinUtil {

	/**
	 * 编写Get请求的方法。但没有参数传递的时候，可以使用Get请求
	 * 
	 * @param url
	 *            需要请求的URL
	 * @return 将请求URL后返回的数据，转为JSON格式，并return
	 */
	@SuppressWarnings({ "resource" })
	public static JSONObject doGetStr(String url)
			throws ClientProtocolException, IOException {
		DefaultHttpClient client = new DefaultHttpClient();// 获取DefaultHttpClient请求
		HttpGet httpGet = new HttpGet(url);// HttpGet将使用Get方式发送请求URL
		JSONObject jsonObject = null;

		HttpResponse response = client.execute(httpGet);// 使用HttpResponse接收client执行httpGet的结果
		HttpEntity entity = response.getEntity();// 从response中获取结果，类型为HttpEntity
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");// HttpEntity转为字符串类型
			jsonObject = JSONObject.fromObject(result);// 字符串类型转为JSON类型
		}
		return jsonObject;
	}

	/**
	 * 编写Post请求的方法。当我们需要参数传递的时候，可以使用Post请求
	 * 
	 * @param url
	 *            需要请求的URL
	 * @param outStr
	 *            需要传递的参数
	 * @return 将请求URL后返回的数据，转为JSON格式，并return
	 */
	@SuppressWarnings({ "resource" })
	public static JSONObject doPostStr(String url, String outStr)
			throws ClientProtocolException, IOException {
		DefaultHttpClient client = new DefaultHttpClient();// 获取DefaultHttpClient请求
		HttpPost httpost = new HttpPost(url);// HttpPost将使用Get方式发送请求URL
		JSONObject jsonObject = null;
		httpost.setEntity(new StringEntity(outStr, "UTF-8"));// 使用setEntity方法，将我们传进来的参数放入请求中
		HttpResponse response = client.execute(httpost);// 使用HttpResponse接收client执行httpost的结果
		String result = EntityUtils.toString(response.getEntity(), "UTF-8");// HttpEntity转为字符串类型
		jsonObject = JSONObject.fromObject(result);// 字符串类型转为JSON类型
		return jsonObject;
	}

	/**
	 * 接入
	 * 
	 * @param req
	 * @param out
	 */
	@SuppressWarnings({ "unused" })
	public static void connect(HttpServletRequest req, PrintWriter out) {
		HttpSession httpSession = req.getSession();
		// 获取参数
		String signature = req.getParameter("signature");// 签名
		String timestamp = req.getParameter("timestamp");// 时间戳
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		// 校验
		List<String> list = new ArrayList<String>();
		list.add("miniyiwei");
		list.add(timestamp);
		list.add(nonce);
		// 排序
		Collections.sort(list);

		// 拼接字符串-------》sha1加密
		StringBuffer buffer = new StringBuffer();
		for (String string : list) {
			buffer.append(string);
		}
		// 使用apache commons codec 加密
		String sha1Str = DigestUtils.shaHex(buffer.toString());
		System.out.println(signature);
		// 对比
		boolean flag = sha1Str.equals(signature);
		if (flag) {
			System.out.println("恭喜你！已成功接入微信,您可以进行微信相关接口开发啦！");
//			out.print(echostr);
			out.flush();
		}

	}
	//处理http请求  requestUrl为请求地址  requestMethod请求方式，值为"GET"或"POST"
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
        StringBuffer buffer=null;
        try{
        URL url=new URL(requestUrl);
        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(requestMethod);
        conn.connect();
        //往服务器端写内容 也就是发起http请求需要带的参数
        if(null!=outputStr){
            OutputStream os=conn.getOutputStream();
            os.write(outputStr.getBytes("utf-8"));
            os.close();
        }
        
        //读取服务器端返回的内容
        InputStream is=conn.getInputStream();
        InputStreamReader isr=new InputStreamReader(is,"utf-8");
        BufferedReader br=new BufferedReader(isr);
        buffer=new StringBuffer();
        String line=null;
        while((line=br.readLine())!=null){
            buffer.append(line);
        }
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }
    
}
